<template>
  <div class="dashboard-container">
    <!-- 统计卡片 -->
    <div class="stats-container">
      <div class="stats-card">
        <div class="stats-header">
          <div class="stats-title">用户总数</div>
          <el-icon class="stats-icon user-icon"><User /></el-icon>
        </div>
        <div class="stats-content">
          <div class="stats-value">{{ statistics.userCount || 0 }}</div>
          <div class="stats-desc">较昨日
            <span :class="statistics.userGrowth >= 0 ? 'stats-up' : 'stats-down'">
              {{ Math.abs(statistics.userGrowth || 0) }}%
              <el-icon v-if="statistics.userGrowth >= 0"><CaretTop /></el-icon>
              <el-icon v-else><CaretBottom /></el-icon>
            </span>
          </div>
        </div>
      </div>
      
      <div class="stats-card">
        <div class="stats-header">
          <div class="stats-title">今日对话</div>
          <el-icon class="stats-icon chat-icon"><ChatDotRound /></el-icon>
        </div>
        <div class="stats-content">
          <div class="stats-value">{{ statistics.todayChats || 0 }}</div>
          <div class="stats-desc">较昨日
            <span :class="statistics.chatGrowth >= 0 ? 'stats-up' : 'stats-down'">
              {{ Math.abs(statistics.chatGrowth || 0) }}%
              <el-icon v-if="statistics.chatGrowth >= 0"><CaretTop /></el-icon>
              <el-icon v-else><CaretBottom /></el-icon>
            </span>
          </div>
        </div>
      </div>
      
      <div class="stats-card">
        <div class="stats-header">
          <div class="stats-title">会员数</div>
          <el-icon class="stats-icon vip-icon"><Crown /></el-icon>
        </div>
        <div class="stats-content">
          <div class="stats-value">{{ statistics.vipCount || 0 }}</div>
          <div class="stats-desc">占总用户 {{ statistics.vipRate || 0 }}%</div>
        </div>
      </div>
      
      <div class="stats-card">
        <div class="stats-header">
          <div class="stats-title">系统状态</div>
          <el-icon class="stats-icon system-icon" :class="{ 'system-error': !systemStatus.normal }">
            <Monitor v-if="systemStatus.normal" />
            <Warning v-else />
          </el-icon>
        </div>
        <div class="stats-content">
          <div class="stats-value">{{ systemStatus.normal ? '正常' : '异常' }}</div>
          <div class="stats-desc">CPU: {{ systemStatus.cpu || 0 }}%</div>
        </div>
      </div>
    </div>
    
    <!-- 图表区域 -->
    <div class="chart-container">
      <div class="chart-row">
        <!-- 用户增长趋势 -->
        <div class="chart-card">
          <div class="chart-header">
            <div class="chart-title">用户增长趋势</div>
          </div>
          <div class="chart-content" ref="userGrowthChart"></div>
        </div>
        
        <!-- 对话量统计 -->
        <div class="chart-card">
          <div class="chart-header">
            <div class="chart-title">对话量统计</div>
          </div>
          <div class="chart-content" ref="chatStatisticsChart"></div>
        </div>
      </div>
      
      <div class="chart-row">
        <!-- 会员/配额销售统计 -->
        <div class="chart-card">
          <div class="chart-header">
            <div class="chart-title">会员/配额销售统计</div>
          </div>
          <div class="chart-content" ref="salesStatisticsChart"></div>
        </div>
        
        <!-- 系统资源使用情况 -->
        <div class="chart-card">
          <div class="chart-header">
            <div class="chart-title">系统资源使用情况</div>
          </div>
          <div class="chart-content" ref="resourceUsageChart"></div>
        </div>
      </div>
    </div>
    
    <!-- 最近活动 -->
    <div class="recent-activities">
      <div class="activities-card">
        <div class="activities-header">
          <div class="activities-title">最近活动</div>
        </div>
        <div class="activities-content">
          <el-table :data="recentActivities" style="width: 100%">
            <el-table-column prop="time" label="时间" width="180" />
            <el-table-column prop="user" label="用户" width="120" />
            <el-table-column prop="action" label="操作" />
            <el-table-column prop="result" label="结果" width="100">
              <template #default="scope">
                <el-tag :type="scope.row.result === '成功' ? 'success' : 'danger'">
                  {{ scope.row.result }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { getSystemInfo, getUserStatistics } from '@/api/system'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { LineChart, BarChart, PieChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
} from 'echarts/components'
import VChart from 'vue-echarts'

// 注册ECharts组件
use([
  CanvasRenderer,
  LineChart,
  BarChart,
  PieChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
])

// 图表引用
const userGrowthChart = ref(null)
const chatStatisticsChart = ref(null)
const salesStatisticsChart = ref(null)
const resourceUsageChart = ref(null)

// 统计数据
const statistics = reactive({
  userCount: 0,
  userGrowth: 0,
  todayChats: 0,
  chatGrowth: 0,
  vipCount: 0,
  vipRate: 0
})

// 系统状态
const systemStatus = reactive({
  normal: true,
  cpu: 0,
  memory: 0,
  disk: 0
})

// 最近活动
const recentActivities = ref([
  { time: '2023-08-10 14:30:25', user: '张三', action: '创建会员订单', result: '成功' },
  { time: '2023-08-10 14:25:18', user: '李四', action: '发送聊天消息', result: '成功' },
  { time: '2023-08-10 14:20:12', user: '王五', action: '购买配额包', result: '成功' },
  { time: '2023-08-10 14:15:05', user: '赵六', action: '登录系统', result: '失败' },
  { time: '2023-08-10 14:10:33', user: '钱七', action: '更新敏感词', result: '成功' }
])

// 图表实例
let userGrowthChartInstance = null
let chatStatisticsChartInstance = null
let salesStatisticsChartInstance = null
let resourceUsageChartInstance = null

// 初始化用户增长趋势图表
const initUserGrowthChart = () => {
  if (!userGrowthChart.value) return
  
  userGrowthChartInstance = echarts.init(userGrowthChart.value)
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '新增用户',
        type: 'line',
        stack: 'Total',
        smooth: true,
        data: [120, 132, 101, 134, 90, 230, 210],
        areaStyle: {
          color: 'rgba(24, 144, 255, 0.2)'
        },
        lineStyle: {
          color: '#1890ff'
        }
      }
    ]
  }
  userGrowthChartInstance.setOption(option)
}

// 初始化对话量统计图表
const initChatStatisticsChart = () => {
  if (!chatStatisticsChart.value) return
  
  chatStatisticsChartInstance = echarts.init(chatStatisticsChart.value)
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '对话量',
        type: 'bar',
        barWidth: '60%',
        data: [820, 932, 901, 934, 1290, 1330, 1320],
        itemStyle: {
          color: '#1890ff'
        }
      }
    ]
  }
  chatStatisticsChartInstance.setOption(option)
}

// 初始化销售统计图表
const initSalesStatisticsChart = () => {
  if (!salesStatisticsChart.value) return
  
  salesStatisticsChartInstance = echarts.init(salesStatisticsChart.value)
  const option = {
    tooltip: {
      trigger: 'item'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: '销售统计',
        type: 'pie',
        radius: '50%',
        data: [
          { value: 1048, name: '会员销售' },
          { value: 735, name: '配额包销售' }
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  salesStatisticsChartInstance.setOption(option)
}

// 初始化系统资源使用情况图表
const initResourceUsageChart = () => {
  if (!resourceUsageChart.value) return
  
  resourceUsageChartInstance = echarts.init(resourceUsageChart.value)
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: ['CPU', '内存', '磁盘']
    },
    yAxis: {
      type: 'value',
      max: 100,
      axisLabel: {
        formatter: '{value}%'
      }
    },
    series: [
      {
        name: '使用率',
        type: 'bar',
        barWidth: '60%',
        data: [systemStatus.cpu, systemStatus.memory, systemStatus.disk],
        itemStyle: {
          color: function(params) {
            const colorList = ['#1890ff', '#52c41a', '#faad14']
            return colorList[params.dataIndex]
          }
        }
      }
    ]
  }
  resourceUsageChartInstance.setOption(option)
}

// 获取系统信息
const getSystemInfoData = async () => {
  try {
    const response = await getSystemInfo()
    if (response.status) {
      systemStatus.normal = response.status.status === 'normal'
      systemStatus.cpu = response.status.cpuUsage || 0
      systemStatus.memory = response.status.memoryUsage || 0
      systemStatus.disk = response.status.diskUsage || 0
      
      // 更新系统资源图表
      if (resourceUsageChartInstance) {
        resourceUsageChartInstance.setOption({
          series: [
            {
              data: [systemStatus.cpu, systemStatus.memory, systemStatus.disk]
            }
          ]
        })
      }
    }
  } catch (error) {
    console.error('获取系统信息失败', error)
  }
}

// 获取用户统计数据
const getUserStatisticsData = async () => {
  try {
    const response = await getUserStatistics()
    if (response) {
      Object.assign(statistics, response)
    }
  } catch (error) {
    console.error('获取用户统计数据失败', error)
  }
}

// 窗口大小改变时重新调整图表大小
const handleResize = () => {
  userGrowthChartInstance?.resize()
  chatStatisticsChartInstance?.resize()
  salesStatisticsChartInstance?.resize()
  resourceUsageChartInstance?.resize()
}

onMounted(async () => {
  // 获取数据
  await getSystemInfoData()
  await getUserStatisticsData()
  
  // 初始化图表
  initUserGrowthChart()
  initChatStatisticsChart()
  initSalesStatisticsChart()
  initResourceUsageChart()
  
  // 监听窗口大小变化
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  // 销毁图表实例
  userGrowthChartInstance?.dispose()
  chatStatisticsChartInstance?.dispose()
  salesStatisticsChartInstance?.dispose()
  resourceUsageChartInstance?.dispose()
  
  // 移除事件监听
  window.removeEventListener('resize', handleResize)
})
</script>

<style lang="scss" scoped>
.dashboard-container {
  padding: var(--spacing-md);
  
  .stats-container {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
    gap: var(--spacing-md);
    margin-bottom: var(--spacing-lg);
    
    .stats-card {
      background: var(--el-bg-color-overlay);
      border-radius: var(--el-border-radius-large);
      box-shadow: var(--el-box-shadow-sm);
      padding: var(--spacing-md);
      transition: all var(--el-transition-duration);
      position: relative;
      overflow: hidden;
      
      &::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        width: 4px;
        height: 100%;
        background: var(--primary-gradient);
      }
      
      &:hover {
        box-shadow: var(--el-box-shadow-md);
        transform: translateY(-2px);
      }
      
      .stats-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: var(--spacing-base);
        
        .stats-title {
          font-size: var(--el-font-size-base);
          color: var(--el-text-color-secondary);
          font-weight: 500;
        }
        
        .stats-icon {
          width: 48px;
          height: 48px;
          border-radius: var(--el-border-radius-large);
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 24px;
          transition: all var(--el-transition-duration);
          
          &:hover {
            transform: scale(1.05);
          }
          
          &.user-icon {
            background: rgba(91, 95, 222, 0.1);
            color: var(--el-color-primary);
          }
          
          &.chat-icon {
            background: rgba(16, 185, 129, 0.1);
            color: var(--el-color-success);
          }
          
          &.vip-icon {
            background: rgba(245, 158, 11, 0.1);
            color: var(--el-color-warning);
          }
          
          &.system-icon {
            background: rgba(16, 185, 129, 0.1);
            color: var(--el-color-success);
            
            &.system-error {
              background: rgba(239, 68, 68, 0.1);
              color: var(--el-color-danger);
            }
          }
        }
      }
      
      .stats-content {
        .stats-value {
          font-size: 32px;
          font-weight: 700;
          color: var(--el-text-color-primary);
          margin-bottom: var(--spacing-sm);
        }
        
        .stats-desc {
          font-size: var(--el-font-size-small);
          color: var(--el-text-color-secondary);
          
          .stats-up {
            color: var(--el-color-success);
            font-weight: 500;
            display: inline-flex;
            align-items: center;
            
            .el-icon {
              margin-right: 2px;
            }
          }
          
          .stats-down {
            color: var(--el-color-danger);
            font-weight: 500;
            display: inline-flex;
            align-items: center;
            
            .el-icon {
              margin-right: 2px;
            }
          }
        }
      }
    }
  }
  
  .chart-container {
    margin-bottom: var(--spacing-lg);
    
    .chart-row {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(500px, 1fr));
      gap: var(--spacing-md);
      margin-bottom: var(--spacing-md);
      
      &:last-child {
        margin-bottom: 0;
      }
      
      .chart-card {
        background: var(--el-bg-color-overlay);
        border-radius: var(--el-border-radius-large);
        box-shadow: var(--el-box-shadow-sm);
        padding: var(--spacing-md);
        transition: all var(--el-transition-duration);
        position: relative;
        overflow: hidden;
        
        &::before {
          content: '';
          position: absolute;
          top: 0;
          left: 0;
          width: 100%;
          height: 3px;
          background: var(--primary-gradient);
        }
        
        &:hover {
          box-shadow: var(--el-box-shadow-md);
          transform: translateY(-2px);
        }
        
        .chart-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: var(--spacing-base);
          
          .chart-title {
            font-size: var(--el-font-size-medium);
            font-weight: 600;
            color: var(--el-text-color-primary);
          }
          
          .chart-actions {
            display: flex;
            gap: var(--spacing-sm);
          }
        }
        
        .chart-content {
          height: 300px;
          position: relative;
        }
      }
    }
  }
  
  .recent-activities {
    .activities-card {
      background: var(--el-bg-color-overlay);
      border-radius: var(--el-border-radius-large);
      box-shadow: var(--el-box-shadow-sm);
      padding: var(--spacing-md);
      transition: all var(--el-transition-duration);
      position: relative;
      overflow: hidden;
      
      &::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 3px;
        background: var(--primary-gradient);
      }
      
      &:hover {
        box-shadow: var(--el-box-shadow-md);
        transform: translateY(-2px);
      }
      
      .activities-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: var(--spacing-base);
        
        .activities-title {
          font-size: var(--el-font-size-medium);
          font-weight: 600;
          color: var(--el-text-color-primary);
        }
        
        .activities-actions {
          display: flex;
          gap: var(--spacing-sm);
        }
      }
      
      .activities-content {
        .el-table {
          --el-table-header-bg-color: var(--el-fill-color-lighter);
          --el-table-row-hover-bg-color: var(--el-fill-color-light);
          
          .el-table__row {
            transition: all var(--el-transition-duration);
            
            &:hover {
              background-color: var(--el-fill-color-light);
            }
          }
        }
      }
    }
  }
}

// 响应式布局
@media (max-width: 576px) {
  .dashboard-container {
    padding: var(--spacing-sm);
    
    .stats-container {
      grid-template-columns: 1fr;
    }
    
    .chart-container {
      .chart-row {
        grid-template-columns: 1fr;
      }
    }
  }
}

@media (min-width: 577px) and (max-width: 768px) {
  .dashboard-container {
    .stats-container {
      grid-template-columns: repeat(2, 1fr);
    }
    
    .chart-container {
      .chart-row {
        grid-template-columns: 1fr;
      }
    }
  }
}

@media (min-width: 769px) and (max-width: 992px) {
  .dashboard-container {
    .stats-container {
      grid-template-columns: repeat(2, 1fr);
    }
    
    .chart-container {
      .chart-row {
        grid-template-columns: repeat(2, 1fr);
      }
    }
  }
}

@media (min-width: 993px) and (max-width: 1200px) {
  .dashboard-container {
    .stats-container {
      grid-template-columns: repeat(3, 1fr);
    }
    
    .chart-container {
      .chart-row {
        grid-template-columns: repeat(2, 1fr);
      }
    }
  }
}

@media (min-width: 1201px) {
  .dashboard-container {
    .stats-container {
      grid-template-columns: repeat(4, 1fr);
    }
    
    .chart-container {
      .chart-row {
        grid-template-columns: repeat(2, 1fr);
      }
    }
  }
}
</style>